//
//  CZComposeView.swift
//  CZVVeiBo
//
//  Created by smile on 2017/8/5.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
import pop
class CZComposeView: UIView {
    
    // 记录mainVc对象
    var target: UIViewController?
    
    // 保存6个按钮
    var composeButtons:[CZComposeButton] = [CZComposeButton]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 设置视图
    private func setupUI(){
        // 设置大小
        self.frame.size = CGSize(width: CZSCREENW, height: CZSCREENH)
        backgroundColor =  randomColor()
        // 添加图片
        addSubview(bgImageView)
        addSubview(sloganImageView)
        
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        sloganImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
       }
        
        addChildButtons()
    }
    // 创建6个按钮
    fileprivate func addChildButtons(){
        // 获取模型数组
        let composeList = getComposePlist()
        // 按钮的宽和高
        let buttonW: CGFloat = 80
        let buttonH: CGFloat = 110
        // 间距
        let buttonMargin: CGFloat = (CZSCREENW - buttonW*3)/4
        for (i, model) in composeList.enumerated(){
            // 计算列和行索引
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            
            // 创建按钮
            let button = CZComposeButton()
            // 设置数据
            button.composeModel = model
            // 监听事件
            button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
            // frame
            button.frame = CGRect(x: buttonMargin + (buttonMargin + buttonW)*col, y: (buttonMargin + buttonH)*row + CZSCREENH, width: buttonW, height: buttonH)
            // image
            button.setImage(UIImage(named:model.icon ?? ""), for: UIControlState.normal)
            button.setTitle(model.title, for: UIControlState.normal)
            // 添加到数组中
            composeButtons.append(button)
            // 添加按钮
            addSubview(button)
        }
    }
    
    // 类方法
    class func show(target: UIViewController){
        let composeView = CZComposeView()
        // 记录
        composeView.target = target
        target.view.addSubview(composeView)
        //执行动画
        composeView.setupComposeButtonsAnim(isUp: true)
    }
    
    // MARK: - 背景图片
    fileprivate lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    // logo
    fileprivate lazy var sloganImageView: UIImageView = UIImageView(imgName: "compose_slogan")
}
// MARK: - 设置6个按钮动画
extension CZComposeView{
    func setupComposeButtonsAnim(isUp: Bool){
        // 设置默认值
        var h: CGFloat = -350
        // 如果是消失
        if !isUp {
            h = 350
            composeButtons = composeButtons.reversed()
        }
        // 设置动画
        for (i, button) in composeButtons.enumerated(){
            // 对象
            let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)!
            // toValue
            anSpring.toValue = CGPoint(x: button.center.x, y: button.center.y + h)
            // beginTime
            anSpring.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 弹力
            anSpring.springBounciness = 10.0
            // 设置动画
            button.pop_add(anSpring, forKey: nil)
        }
    }
}

// MARK: - 读取plist文件内容
extension CZComposeView{
    func getComposePlist() -> [CZComposeModel]{
        // 文件名
        let file = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        // 获取plist转数组
        let plistArray = NSArray(contentsOfFile: file)!
        // 模型数组
        let tempList = NSArray.yy_modelArray(with: CZComposeModel.self, json: plistArray) as! [CZComposeModel]
        return tempList
    }
}

extension CZComposeView{
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.setupComposeButtonsAnim(isUp: false)
        // 延迟
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            self.removeFromSuperview()
        }
    }
}
// MARK: - 监听事件
extension CZComposeView{
    @objc fileprivate func buttonClick(button: CZComposeButton){
        // 设置动画
        UIView.animate(withDuration: 0.25, animations: {
            // 遍历按钮数组
            for composebutton in self.composeButtons{
                // 透明度
                composebutton.alpha = 0.2
                // 判断点击的按钮
                if button == composebutton {
                    // 放大动画
                    composebutton.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    // 缩小动画
                    composebutton.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
        }) { (_) in
            // 恢复原状
            UIView.animate(withDuration: 0.25, animations: {
                
                // 遍历按钮数组
                for composebutton in self.composeButtons{
                    // 透明度
                    composebutton.alpha = 1
                    composebutton.transform = CGAffineTransform.identity
                }
                
            }, completion: { (_) in
                // 分别来弹出控制器
                // 判断classname是否为nil
                guard let classname = button.composeModel?.classname else{
                    return
                }
                // 通过classname得到对应的class 是否可以转成 UIViewController.Type
                guard let type = NSClassFromString(classname) as? UIViewController.Type else{
                    return
                }
                // 通过UIViewController.Type 得到对应的类
                let vc = type.init()
                
                // 导航控制器
                let nav = CZNavigationController(rootViewController: vc)
                // 模态形式弹出控制器
                self.target?.present(nav, animated: true, completion: {
                    // composeView 移除
                    self.removeFromSuperview()
                })
            })
        }
    }
}
